/**
 * Copyright (c) 2018, Alex. All rights reserved.
 */
package com.oschina.bottle.poi.exp;

import com.oschina.bottle.poi.Exporter;
import com.oschina.bottle.poi.FileInfo;
import com.oschina.bottle.poi.Head;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * csv导出
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2018/2/5
 * @since 1.0
 */
public class CsvExporter implements Exporter {

    /**
     * 列分隔符
     */
    private static final String CSV_CO_SEPARATOR = ",";
    /**
     * 行分隔符
     */
    private static final String CSV_RN_SEPARATOR = "\r\n";


    @Override
    public void export(FileInfo fileInfo) throws IOException {
        StringBuilder sb = new StringBuilder();
        //抬头行
        for (int a = 0; a < fileInfo.getHeaderIndex(); a++) {
            sb.append(CSV_RN_SEPARATOR);
        }

        //标题行
        if(fileInfo.isShowHeader()) {
            for (Head head : fileInfo.getHeads()) {
                sb.append(head.getColumnName()).append(CSV_CO_SEPARATOR);
            }
            sb.append(CSV_RN_SEPARATOR);
        }

        for (Map<String, Object> item : fileInfo.getData()) {
            for (Head head : fileInfo.getHeads()) {
                String value = dateToStr(item.get(head.getFieldName()));
                sb.append(value).append(CSV_CO_SEPARATOR);
            }
            sb.append(CSV_RN_SEPARATOR);
        }
        OutputStream out = fileInfo.getOutput();
        try {
            out.write(sb.toString().getBytes("UTF-8"));
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    public static String dateToStr(Object obj) {
        if (obj == null) {
            return "";
        }
        if (obj instanceof java.util.Date) {
            DateFormat df = new SimpleDateFormat(dayPatterns);
            return df.format((java.util.Date) obj);
        }
        return obj.toString();
    }

    public final static String dayPatterns = "yyyy-MM-dd";
}
